import React, { useState, useEffect } from 'react'
import { View, Text, Image, Progress } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useAppContext } from '../../store'
import { pointsUtils } from '../../utils/pointsUtils'
import './index.scss'

interface MemberCenterProps {
  userId?: string;
}

interface MemberInfo {
  level: number;
  name: string;
  pointsMultiplier: number;
  benefits: string[];
  nextLevel?: {
    level: number;
    name: string;
    pointsNeeded: number;
  };
}

const MemberCenter: React.FC<MemberCenterProps> = ({ userId }) => {
  const { state } = useAppContext()
  const [memberInfo, setMemberInfo] = useState<MemberInfo | null>(null)
  const [currentPoints, setCurrentPoints] = useState(0)
  const [loading, setLoading] = useState(true)
  
  // 使用当前登录用户或传入的userId
  const currentUserId = userId || state.currentUser?.id
  
  useEffect(() => {
    if (currentUserId) {
      fetchMemberInfo()
    }
  }, [currentUserId])
  
  const fetchMemberInfo = async () => {
    if (!currentUserId) return
    
    setLoading(true)
    try {
      // 获取会员信息
      const info = await pointsUtils.getUserMemberInfo(currentUserId)
      setMemberInfo(info)
      
      // 获取当前积分
      const points = await pointsUtils.getUserPoints(currentUserId)
      setCurrentPoints(points)
    } catch (error) {
      console.error('获取会员信息失败:', error)
      Taro.showToast({
        title: '获取会员信息失败',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }
  
  // 计算进度百分比
  const calculateProgress = (): number => {
    if (!memberInfo || !memberInfo.nextLevel) return 100
    
    const currentLevelPoints = memberInfo.level > 1 
      ? memberInfo.nextLevel.pointsNeeded + currentPoints 
      : currentPoints
    
    const nextLevelPoints = memberInfo.nextLevel.pointsNeeded + currentPoints
    
    // 防止除以零
    if (nextLevelPoints === 0) return 0
    
    // 计算百分比，最大100%
    return Math.min(100, (currentLevelPoints / nextLevelPoints) * 100)
  }
  
  if (loading) {
    return (
      <View className='member-center-loading'>
        <Text>加载中...</Text>
      </View>
    )
  }
  
  if (!memberInfo) {
    return (
      <View className='member-center-error'>
        <Text>无法获取会员信息</Text>
      </View>
    )
  }
  
  return (
    <View className='member-center'>
      {/* 会员卡片 */}
      <View className={`member-card level-${memberInfo.level}`}>
        <View className='member-card-header'>
          <View className='member-info'>
            <Text className='member-name'>{state.currentUser?.name || '用户'}</Text>
            <Text className='member-level'>{memberInfo.name}</Text>
          </View>
          <View className='member-points'>
            <Text className='points-value'>{currentPoints}</Text>
            <Text className='points-label'>积分</Text>
          </View>
        </View>
        
        {/* 会员等级进度 */}
        {memberInfo.nextLevel && (
          <View className='member-progress'>
            <Progress 
              percent={calculateProgress()} 
              strokeWidth={4} 
              activeColor='#FFD700' 
              backgroundColor='rgba(255,255,255,0.3)' 
            />
            <Text className='progress-text'>
              距离{memberInfo.nextLevel.name}还需{memberInfo.nextLevel.pointsNeeded}积分
            </Text>
          </View>
        )}
        
        {/* 会员特权 */}
        <View className='member-benefits'>
          <Text className='benefits-title'>会员特权</Text>
          <View className='benefits-list'>
            {memberInfo.benefits.map((benefit, index) => (
              <View key={index} className='benefit-item'>
                <Text>{benefit}</Text>
              </View>
            ))}
          </View>
        </View>
        
        {/* 积分倍率 */}
        <View className='points-multiplier'>
          <Text>当前积分倍率: {memberInfo.pointsMultiplier}x</Text>
        </View>
      </View>
      
      {/* 积分操作按钮 */}
      <View className='points-actions'>
        <View className='action-button' onClick={() => Taro.navigateTo({ url: '/pages/points/history' })}>
          <Text>积分明细</Text>
        </View>
        <View className='action-button' onClick={() => Taro.navigateTo({ url: '/pages/points/rules' })}>
          <Text>积分规则</Text>
        </View>
      </View>
    </View>
  )
}

export default MemberCenter 